package com.zhuangjie.order.controller;

import com.zhaungjie.base.conduit.R;
import com.zhuangjie.base.constant.ModuleSecurityNames;
import com.zhuangjie.order.dto.RiderLocationUpdateDTO;
import com.zhuangjie.order.service.UserSSEService;
import com.zhuangjie.security.annotations.OnlySystemCall;
import com.zhuangjie.security.annotations.PublicAPI;
import com.zhuangjie.security.provider.UserProvider;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.io.IOException;

/**
 * 用户SSE 控制器
 */
@RequestMapping("/sse/user")
@RestController
@PublicAPI(modules = {ModuleSecurityNames.USER})
public class UserSSEController {
    @Autowired
    private UserSSEService userSSEService;

    @GetMapping("/on")
    public SseEmitter on() throws IOException {
        Long userId = UserProvider.currentUserId();
        return userSSEService.listen(userId);
    }

    @GetMapping("/close")
    public void close() {
        Long userId = UserProvider.currentUserId();
        userSSEService.remove(userId);
    }

    @PutMapping("/order-state-change")
    @ApiOperation("提醒用户端，订单状态已经改变")
    @PublicAPI
    @OnlySystemCall
    public R orderStateChange(@RequestParam(value = "userId", required = false) Long userId, @RequestParam("orderId") Long orderId) {
        userSSEService.orderStateChange(userId,orderId);
        return R.ok();
    }

    @PutMapping("/rider-location-update")
    @ApiOperation("骑手位置更新")
    @PublicAPI
    @OnlySystemCall
    public R riderLocationUpdate(@Valid @RequestBody RiderLocationUpdateDTO riderLocationUpdateDTO) {
        return R.capture(()->userSSEService.riderLocationUpdate(riderLocationUpdateDTO));
    }
}
